import axios from 'axios'
import { Message } from 'element-ui'
import qs from 'qs'
import store from '@/store'
import { clearCookie } from '@/methods/utils'
import router from '@/router'

const instance = axios.create({
	baseURL: axios.defaults.baseURL,
	timeout: 10000,
	responseType: 'json',
	withCredentials: true, // 是否允许带cookie这些
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded'
		// 'Content-Type': 'application/json;charset=UTF-8'
	}
})

// 添加请求拦截器
instance.interceptors.request.use(
	config => {
		// 在发送请求之前做些什么
		config.headers['Accept'] = 'application/json;charset=UTF-8'
		config.headers['Content-Type'] =
			config.headers['Content-Type'] || 'application/x-www-form-urlencoded'
		if (store.getters?.token !== '') config.headers['token'] = store.getters?.token
		// console.log(config)
		return config
	},
	error => {
		// 对请求错误做些什么
		return Promise.reject(error)
	}
)

// 添加响应拦截器
instance.interceptors.response.use(
	response => {
		// 对响应数据做点什么
		// console.log(response)
		if (response?.data?.code + '' === '4001') {
			Message({ message: '登录失效！', type: 'error' })
			store.commit('HANDLE_LOGIN_STATUS', false)
			router.push('/login')
		}
		return response
	},
	error => {
		// 对响应错误做点什么
		if (error.response?.status === 401) {
			Message({ message: '您还没有登录，或者登录已过期，需要重新登录！', type: 'error' })
			clearCookie()
			store.commit('HANDLE_LOGIN_STATUS', false)
			router.push('/login')
		}
		return Promise.reject(error)
	}
)

/*ajax请求工具封装，封装了get，post，put，delete四种请求
 *@param url 请求地址
 *@param method 请求类型
 *@param data 数据
 *@param config 配置内容
 */
const request = (url, method = 'GET', data = {}, config = {}) => {
	if (process.env.NODE_ENV === 'production') {
		instance.defaults.baseURL = '/api'
	} else if (process.env.NODE_ENV === 'development') {
		instance.defaults.baseURL = '/api'
	}
	return new Promise((resolve, reject) => {
		let options = {
			url,
			method,
			...config
		}
		switch (method.toLowerCase()) {
			case 'get':
				options.params = data
				break
			case 'post':
			case 'put':
			case 'delete':
				config?.headers && config?.headers['Content-Type'] === 'application/json;charset=UTF-8'
					? (options.data = data)
					: (options.data = qs.stringify(data))
				break
		}

		instance(options).then(
			res => {
				const {
					status,
					data,
					data: { code, msg: message }
				} = res
				if (status === 200) {
					if (code === 0) {
						resolve(data)
					} else if (code == 401) {
						Message({ message: '您还没有登录，或者登录已过期，需要重新登录！', type: 'error' })
						clearCookie()
						store.commit('HANDLE_LOGIN_STATUS', false)
						router.push('/login')
					} else {
						Message({ type: 'error', message })
					}
				} else if (status - 200 > 0 && status - 200 < 100) {
					resolve(res)
				} else {
					reject(res)
				}
			},
			err => {
				reject(err)
			}
		)
	})
}

export default request
